package hust.cs.javacourse.search.parse.impl;

import hust.cs.javacourse.search.index.AbstractTermTuple;
import hust.cs.javacourse.search.index.impl.TermTuple;
import hust.cs.javacourse.search.index.impl.Term;
import hust.cs.javacourse.search.parse.AbstractTermTupleScanner;
import hust.cs.javacourse.search.util.Config;
import hust.cs.javacourse.search.util.StringSplitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TermTupleScanner extends AbstractTermTupleScanner {
    /**
     * 记录term在当前文件中的当前位置，初始为0
     */
    private int curPos;

    /**
     * TermTuple的集合
     */
    private List<TermTuple> tuples = new ArrayList<>();

    /**
     * 构造函数
     * 将输入流分成独立的word，然后生成term，再将term和其位置送进termTuple，加入到tuples中
     * @param input：指定输入流对象，应该关联到一个文本文件
     */
    public TermTupleScanner(BufferedReader input) {
        super(input);
        try{
            String str = null;
            while((str=input.readLine())!=null){
                StringSplitter splitter = new StringSplitter();
                splitter.setSplitRegex(Config.STRING_SPLITTER_REGEX);
                List<String> words = splitter.splitByRegex(str);
                for(int i=0; i<words.size(); i++){
                    if(!words.get(i).equals("")){
                        tuples.add(new TermTuple(new Term(words.get(i).toLowerCase()), curPos));
                        curPos++;
                    }
                }
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public void close(){
        super.close();
    }

    @Override
    public AbstractTermTuple next(){
        if(tuples.size()!=0){
            return tuples.remove(0);
        }
        else return null;
    }
}
